﻿using System.IO;
using System.Windows.Forms;
using Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.PowerPoint.STAMP.Core;
using Microsoft.Office.PowerPoint.STAMP.Properties;
using Application = Microsoft.Office.Interop.PowerPoint.Application;

namespace Microsoft.Office.PowerPoint.STAMP.Command
{
    /// <summary>
    /// Shows a <see cref="SaveFileDialog"/> and exports the captions to the selected location.
    /// </summary>
    public class ExportCommand : ICommand
    {
        /// <summary>
        /// Executes this instance.
        /// </summary>
        public void Execute()
        {
            SaveFileDialog dialog = new SaveFileDialog
                                        {
                                            Title = Resources.ExportToTTMLDialog_Title,
                                            Filter = Resources.ExportToTTMLDialog_Filter,
                                            DefaultExt = "*.ttml"
                                        };
            DialogResult result = dialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                StampSlide slide = new StampSlide(ActiveSlide);
                CaptionItemsList captionItemsList = slide.RetrieveCaptions(SelectedShape);

                CaptionExporter captionExporter = new CaptionExporter(captionItemsList.CaptionItems);
                string exportToTTML = captionExporter.ExportToTTML();
                using (StreamWriter streamWriter = new StreamWriter(dialog.OpenFile()))
                {
                    streamWriter.Write(exportToTTML);
                    streamWriter.Flush();
                }
            }
        }


        /// <summary>
        /// Gets the currently active slide.
        /// </summary>
        private static Slide ActiveSlide
        {
            get { return CurrentApplication.ActiveWindow.View.Slide; }
        }

        /// <summary>
        /// Gets the slected media shape for wqihch we edit captions.
        /// </summary>
        private static StampMediaShape SelectedShape
        {
            get { return new StampMediaShape(CurrentApplication.ActiveWindow.Selection.ShapeRange[1]); }
        }

        /// <summary>
        /// Gets the powerpoint application the Addin is running in.
        /// </summary>
        private static Application CurrentApplication
        {
            get { return Globals.ThisAddIn.Application; }
        }
    }
}